package com.battery.web.controller.system.battery;

import java.math.BigDecimal;
import java.util.List;

import com.battery.common.core.domain.Ztree;
import com.battery.common.enums.AccountTypeEnum;
import com.battery.common.utils.MobileEmailUtils;
import com.battery.system.domain.BO.PartnerBO;
import com.battery.system.domain.PartnerInstall;
import com.battery.system.domain.ProxyUser;
import com.battery.system.domain.VO.PartnerVO;
import com.battery.system.service.battery.IMerchantService;
import com.battery.system.service.battery.IPartnerInstallService;
import com.battery.system.service.battery.IProxyUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.battery.common.annotation.Log;
import com.battery.common.enums.BusinessType;
import com.battery.system.domain.Partner;
import com.battery.system.service.battery.IPartnerService;
import com.battery.common.core.controller.BaseController;
import com.battery.common.core.domain.AjaxResult;
import com.battery.common.utils.poi.ExcelUtil;
import com.battery.common.core.page.TableDataInfo;

/**
 * 合作商Controller
 *
 * @author battery
 * @date 2021-01-21
 */
@Controller
@RequestMapping("/system/partner")
public class PartnerController extends BaseController {
    private String prefix = "system/partner";

    @Autowired
    private IPartnerService partnerService;


    @Autowired
    private IProxyUserService proxyUserService;

    @Autowired
    private IPartnerInstallService partnerInstallService;


    @Autowired
    private IMerchantService merchantService;

    @RequiresPermissions("system:partner:view")
    @GetMapping()
    public String partner() {
        return prefix + "/partner";
    }

    /**
     * 查询合作商列表
     */
    @RequiresPermissions("system:partner:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(PartnerBO partnerBO) {
        startPage();
//        List<Partner> list = partnerService.selectPartnerList(partner);
        List<PartnerVO> list = partnerService.selectPartnerVOList(partnerBO);
        return getDataTable(list);
    }


    /**
     * 查询营业额TOP6
     *
     * @return
     */
    @PostMapping("/partnerTop6")
    @ResponseBody
    public List<Partner> partnerTop6() {
        return partnerService.selectPartnerTop6List();
    }


    /**
     * 导出合作商列表
     */
    @RequiresPermissions("system:partner:export")
    @Log(title = "合作商", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Partner partner) {
        List<Partner> list = partnerService.selectPartnerList(partner);
        ExcelUtil<Partner> util = new ExcelUtil<Partner>(Partner.class);
        return util.exportExcel(list, "partner");
    }

    /**
     * 新增合作商
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存合作商
     */
    @RequiresPermissions("system:partner:add")
    @Log(title = "合作商", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Partner partner) {

        if (partner.getSubjectType() == null) {
            return error("请选择合作商类型");
        }

        if (StringUtils.isBlank(partner.getFullName())) {
            return error("请填写合作商姓名");
        }

        if (StringUtils.isBlank(partner.getPhone())) {
            return error("请填写合作商联系方式");
        }

        if (!MobileEmailUtils.checkMobileIsOk(partner.getPhone())) {
            return error("请输入合法的手机号");
        }

        boolean existPhone = proxyUserService.checkPhoneExist(partner.getPhone(), AccountTypeEnum.PARTNER.getCode());
        if (existPhone) {
            return error("该手机号已被注册使用");
        }

        // 平台分润比例
        if (partner.getProjectShareRatio() == null) {
            return error("请填写平台分润比例");
        }

        if (partner.getProjectShareRatio().compareTo(BigDecimal.ZERO) < 0) {
            return error("平台分润比例不能小于0");
        }

        return toAjax(partnerService.addTopLevelPartner(partner));
    }

    /**
     * 修改合作商
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        Partner partner = partnerService.selectPartnerById(id);
        mmap.put("partner", partner);
        return prefix + "/edit";
    }


    /**
     * 跳转到设置页面
     *
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping("/putUpBase/{id}")
    public String putUpBase(@PathVariable("id") String id, ModelMap mmap) {
        PartnerInstall partnerInstall = partnerInstallService.selectByPrimaryKey(id);
        Partner partner = partnerService.selectByPrimaryKey(id);
        PartnerBO partnerBO = new PartnerBO();
        partnerBO.setPartnerId(partner.getId());
        partnerBO.setTxBrokerage(partnerInstall.getTxBrokerage());
        partnerBO.setTxMinPermit(partnerInstall.getTxMinPermit());
        partnerBO.setOrderFreeMinute(partnerInstall.getOrderFreeMinute());
        partnerBO.setDailyOrderLimit(partnerInstall.getDailyOrderLimit());
        partnerBO.setmBl(partnerInstall.getmBl());

        partnerBO.setIcePoint(partner.getIcePoint());
        partnerBO.setFrozenMoney(partner.getFrozenMoney());

        mmap.put("partnerInstall", partnerBO);
        return prefix + "/putUpBase";
    }

    @RequiresPermissions("system:partner:putUpBase")
    @Log(title = "合作商", businessType = BusinessType.UPDATE)
    @PostMapping("/putUpBase")
    @ResponseBody
    public AjaxResult putUpBase(PartnerBO partnerInstall) {
        if (partnerInstall.getPartnerId() == null) {
            return error("合作商ID为空");
        }
        if (partnerInstall.getTxBrokerage() == null) {
            return error("请填写提现手续费！");
        }
        if (partnerInstall.getTxBrokerage().compareTo(BigDecimal.ZERO) < 0 || partnerInstall.getTxBrokerage().subtract(new BigDecimal(100)).compareTo(BigDecimal.ZERO) > 0) {
            return error("提现手续费不能小于0，且不能大于100");
        }

        if (partnerInstall.getTxMinPermit() == null) {
            return error("请填写提现允许最小金额！");
        }

        if (partnerInstall.getTxMinPermit().compareTo(BigDecimal.ZERO) < 0) {
            return error("提现允许最小金额不能小于0");
        }

        if (partnerInstall.getOrderFreeMinute() == null) {
            return error("请填写-‘VIP每单前X分钟免费’");
        }

        if (partnerInstall.getOrderFreeMinute() < 0) {
            return error("‘VIP每单前X分钟免费’不能小于0");
        }

        if (partnerInstall.getDailyOrderLimit() == null) {
            return error("请填写‘每天免费订单数’！");
        }
        if (partnerInstall.getDailyOrderLimit() < 0) {
            return error("‘每天免费订单数’不能小于0！");
        }

        if (partnerInstall.getIcePoint() == null) {
            return error("冻结积分不能为空");
        }

        if (partnerInstall.getIcePoint() < 0) {
            return error("冻结金额不能小于0");
        }

        if (partnerInstall.getFrozenMoney() == null) {
            return error("已冻结金额不能为空");
        }

        if (partnerInstall.getFrozenMoney().compareTo(BigDecimal.ZERO) < 0) {
            return error("已冻结金额不能小于0");
        }

        if (partnerInstall.getmBl() == null) {
            return error("M比例不能为空");
        }

        if (partnerInstall.getmBl() < 0) {
            return error("M比例不能小于0");
        }

        return toAjax(partnerInstallService.setUpPartner(partnerInstall));
    }

    /**
     * 查看详情
     */
    @GetMapping("/seeDetail/{id}")
    public String seeDetail(@PathVariable("id") String id, ModelMap mmap) {
        Partner partner = partnerService.selectPartnerById(id);
        mmap.put("partner", partner);
        return prefix + "/seeDetail";
    }

    /**
     * 跳转到统计分析页面
     *
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping("/statisticalAnalysis/{id}")
    public String statisticalAnalysis(@PathVariable("id") String id, ModelMap mmap) {
        PartnerVO partnerVO = partnerService.selectStatisticalAnalysisVo(id);
        mmap.put("partnerId", id);
        mmap.put("partnerVO", partnerVO);
        return prefix + "/statisticalAnalysis";
    }


    /**
     * 设备营业额
     *
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping("/devIncomes/{id}")
    public String devIncomes(@PathVariable("id") String id, ModelMap mmap) {
        mmap.put("partnerId", id);
        return prefix + "/devIncomes";
    }


    /**
     * 修改保存合作商
     */
    @RequiresPermissions("system:partner:edit")
    @Log(title = "合作商", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Partner partner) {

        if (partner.getSubjectType() == null) {
            return error("请选择合作商类型");
        }

        if (StringUtils.isBlank(partner.getFullName())) {
            return error("请填写合作商姓名");
        }

        if (StringUtils.isBlank(partner.getPhone())) {
            return error("请填写合作商联系方式");
        }

        if (!MobileEmailUtils.checkMobileIsOk(partner.getPhone())) {
            return error("请输入合法的手机号");
        }


        // 校验手机号是否被占用
        ProxyUser proxyUser = proxyUserService.selectOneByAccount(partner.getPhone(), AccountTypeEnum.PARTNER.getCode());
        if (proxyUser != null && !partner.getId().equals(proxyUser.getAccountId())) {
            return error("该手机号已被注册使用");
        }

        // 平台分润比例
        if (partner.getProjectShareRatio() == null) {
            return error("请填写平台分润比例");
        }

        if (partner.getProjectShareRatio().compareTo(BigDecimal.ZERO) < 0) {
            return error("平台分润比例不能小于0");
        }

        return toAjax(partnerService.updateTopLevelPartner(partner));
    }

    /**
     * 删除合作商
     */
    @RequiresPermissions("system:partner:remove")
    @Log(title = "合作商", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        if (StringUtils.isBlank(ids)) {
            return error("ids为空");
        }
        if (ids.contains(",")) {
            return error("暂时不支持批量操作");
        }
        String id = ids;
        // 解约合作商，需要查询该合作商之下是否存在合作商
        int countChildren = partnerService.selectCountByParentId(id);
        if (countChildren > 0) {
            // 该合作商存在下级直营合作商，不可删除
            return error("无法解约，该合作商存在下级直营合作商");
        }

        int countMerchant = merchantService.selectDirectCountByPartnerId(id);
        if (countMerchant > 0) {
            return error("无法解约，该合作商存在直营商户");
        }
        return toAjax(partnerService.deleteLogicPartnerById(id));
    }

    /**
     * 选择合作商树
     */
    @GetMapping(value = {"/selectPartnerTree/{id}", "/selectPartnerTree/"})
    public String selectPartnerTree(@PathVariable(value = "id", required = false) String id, ModelMap mmap) {
        if (StringUtils.isNotBlank(id)) {
            mmap.put("partner", partnerService.selectPartnerById(id));
        }
        return prefix + "/tree";
    }


    /**
     * 仅展示该合作商的上级跟下级
     *
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping(value = {"/selectPartnerTreeForSelf/{id}", "/selectPartnerTreeForSelf/"})
    public String selectPartnerTreeForSelf(@PathVariable(value = "id", required = false) String id, ModelMap mmap) {
        if (StringUtils.isNotBlank(id)) {
            mmap.put("partner", partnerService.selectPartnerById(id));
        }
        return prefix + "/treeSelf";
    }


    /**
     * 加载合作商树列表 仅展示该合作商的上级跟下级
     */
    @GetMapping(value = {"/treeDataSelf/{id}", "/treeDataSelf/"})
    @ResponseBody
    public List<Ztree> treeDataSelf(@PathVariable(value = "id", required = false) String id) {
        List<Ztree> ztrees = partnerService.selectPartnerTreeSelf(id);
        return ztrees;
    }


    /**
     * 加载合作商树列表
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData() {

        List<Ztree> ztrees = partnerService.selectPartnerTree();
        return ztrees;
    }


    /**
     * 选择顶级合作商
     *
     * @return
     */
    @GetMapping("/headPartners")
    public String headPartners() {
        return prefix + "/headPartners";
    }


    /**
     * 查询
     *
     * @return
     */
    @PostMapping("/headPartnersList")
    @ResponseBody
    public TableDataInfo headPartnersList() {
        startPage();
        List<PartnerVO> list = partnerService.selectHeadPartnerVOList();
        return getDataTable(list);
    }

}
